﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EzDesk.AppWebPortal.Code;
using System.Net;
using System.IO;
using System.Text;
using EzDesk.Core;
using System.Collections.Specialized;
using System.Text.RegularExpressions;
using System.Diagnostics;
using EzDesk.AppWebPortal.AppPortal;
using System.Web.Security;

namespace EzDesk.AppWebPortal.Controllers
{
    public class AppPortalController : Controller
    {
        private IAppPortalService _appPortalService;

        public AppPortalController(IAppPortalService appPortalService)
        {
            this._appPortalService = appPortalService;
        }

        // todo: 使用DI重构
        public AppPortalController()
            : this(new AppPortalServiceClient()){
        }

        public ActionResult TokenLogon()
        {
            var ez_token = Request.Cookies["ez_auth_token"];
            try
            {
                Guid userId = _appPortalService.GetUserIdByToken(ez_token.Value);
                FormsAuthentication.RedirectFromLoginPage(userId.ToString(), false);
            }
            catch (Exception ex)
            {
                throw new Exception("Token验证失败，可能是非法操作！", ex);
            }
            return null;
        }


        [ClientAuthorize]
        public ActionResult DirectPortal(string appName)
        {
            string httpMethod = Request.GetHttpMethodOverride(); // 当前的HttpMethod
            if (httpMethod == "POST")
            {
                throw new Exception("POST请求不能Redirect");
            }

            string userAgentStr = getUserAgentTypeFronUserAgentString(Request.UserAgent);

            string funcUrl = Request.Url.PathAndQuery.Remove(0, appName.Length + 1);

            string targetUrl = string.Format("http://{0}{1}",
                _appPortalService.GetAppDomainName(appName, userAgentStr),
                funcUrl
                );

            return Redirect(targetUrl);
        }

        [ClientAuthorize]
        public ActionResult PagePortal(string appName)
        {
            validateAppName(appName);

            string httpMethod = Request.GetHttpMethodOverride(); // 当前的HttpMethod
            string userAgentStr = getUserAgentTypeFronUserAgentString(Request.UserAgent);

            string funcUrl = Request.Url.PathAndQuery.Remove(0, appName.Length + 1 + 5);

            string targetUrl = string.Format("http://{0}{1}",
                _appPortalService.GetAppDomainName(appName, userAgentStr),
                funcUrl
                );


            List<KeyValuePair<string, string>> formParameters = null;
            if (Request.Form != null)
            {
                formParameters = new List<KeyValuePair<string, string>>();
                foreach (var key in Request.Form.AllKeys)
                {
                    formParameters.Add(new KeyValuePair<string, string>(key, Request.Form[key]));
                }
            }
            HttpContent httpContent = _appPortalService.GetPortalRequests(httpMethod, targetUrl, appName, new Guid(User.Identity.Name), formParameters);

            ViewData["Html"] = httpContent.Content;
            return View(string.Format("{0}{1}", userAgentStr, "portal"));
        }

        [ClientAuthorize]
        public ActionResult AjaxPortal(string appName)
        {
            validateAppName(appName);

            string httpMethod = Request.GetHttpMethodOverride(); // 当前的HttpMethod
            string userAgentStr = getUserAgentTypeFronUserAgentString(Request.UserAgent);

            string funcUrl = Request.Url.PathAndQuery.Remove(0, appName.Length + 1 + 5);

            string targetUrl = string.Format("http://{0}{1}",
                _appPortalService.GetAppDomainName(appName, userAgentStr),
                funcUrl
                );
            
            List<KeyValuePair<string, string>> formParameters = null;
            if (Request.Form != null)
            {
                formParameters = new List<KeyValuePair<string, string>>();
                foreach (var key in Request.Form.AllKeys)
                {
                    formParameters.Add(new KeyValuePair<string, string>(key, Request.Form[key]));
                }
            }
            HttpContent httpContent = _appPortalService.GetPortalRequests(httpMethod, targetUrl, appName, new Guid(User.Identity.Name), formParameters);

            return new ContentResult()
            {
                Content = httpContent.Content,
                ContentType = httpContent.ContentType,
                ContentEncoding = Encoding.UTF8,
            };
        }

        private void validateAppName(string appName)
        {
            // 验证app是否存在
            var app = _appPortalService.GetAppByName(appName);
            if (app == null)
            {
                throw new Exception("App验证失败，可能是Url错误");
            }
        }


        private string getUserAgentTypeFronUserAgentString(string userAgent)
        {
            //todo: 为了测试做一个小的stub 在chrome下使用手机客户端，其它浏览器都使用桌面客户端
            
            string agentType = "GenericMobile";
            if (!userAgent.Contains("Chrome"))
            {
                agentType = "DesktopClient";
            }
            return agentType;
            //return "GenericMobile";
        }

        
    }
}
